package ctu.kfad.run.memory;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

public class FieldValueConverter {

    public static final byte FALSE = 0x00;
    public static final byte TRUE = 0x01;
    public static final int INT_BYTE_SIZE = Integer.SIZE / Byte.SIZE;
    public static final int REFERENCE_BYTE_SIZE = INT_BYTE_SIZE;
    public static final int BYTE_BYTE_SIZE = 1;

    public static int toInt(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getInt();
    }

    public static byte[] toBytes(int value) {
        return ByteBuffer.allocate(INT_BYTE_SIZE).putInt(value).array();
    }

    public static boolean toBoolean(byte[] bytes) {
        return bytes[0] == TRUE;
    }

    public static byte[] toBytes(boolean value) {
        return new byte[]{value ? TRUE : FALSE};
    }


    public static byte[] toBytes(String value) {
        try {
            return value.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("You have to support UTF-8 encoding");
        }
    }

    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("You have to support UTF-8 encoding");
        }
    }

}
